<script setup>
import * as echarts from 'echarts';
import { onBeforeUnmount, onMounted, onUnmounted, ref, watch } from 'vue';
import useDataStore from '~/src/store';
import { storeToRefs } from 'pinia';
import { getUserArticleAPI, updateUserTextAPI } from '@/apis/user'
import { getUserInfoAPI } from '~/src/apis/home';
import { followListAPI } from '../../apis/follow';
import { nyr } from '~/src/utils/tool';
import { onBeforeRouteUpdate, useRouter } from 'vue-router';

defineOptions({
    name: 'User'
})

const AVATAR_URL = import.meta.env.VITE_AVATAR_URL

const router = useRouter()
/* -------------------------------- 获取用户个人信息 -------------------------------- */
const dataStore = useDataStore()
const { userInfo, isMobile } = storeToRefs(dataStore)


/* ---------------------------------- 文章分类 ---------------------------------- */
let activeName = ref('first')   // 导航名
let articleList = ref([])       // 文章列表
let articleListCopy = ref([])   // 文章列表副本
let echartsXList = ref([])      // 图表中的x轴列表,10篇
let echartsYLike = ref([])      // 图表中的y轴的点赞数据
let echartsYCollect = ref([])     // 图表中的y轴的收藏数据
// 请求文章信息
const getUserArticleAction = async () => {
    let data = await getUserArticleAPI(userInfo.value.user_id)
    if (data.code === 200) {
        // console.log('datadata', data.data);
        articleList.value = data.data
        articleListCopy.value = data.data
        // 按时间排序后取最近的10篇
        echartsXList.value = data.data.sort((a, b) => b.article_time - a.article_time).slice(0, 10).reverse().map(item => item.article_title)
        echartsYLike.value = data.data.sort((a, b) => b.article_time - a.article_time).slice(0, 10).reverse().map(item => item.article_like)
        echartsYCollect.value = data.data.sort((a, b) => b.article_time - a.article_time).slice(0, 10).reverse().map(item => item.article_collect)

        initMyChart()
    }
}
onMounted(() => {
    // // 检查 localStorage 中是否存在标记
    // const hasRefreshed = localStorage.getItem('hasRefreshed');
    // if (hasRefreshed !== 'refresh') {
    //     // 如果没有标记，刷新页面
    //     setTimeout(() => {
    //         localStorage.setItem('hasRefreshed', 'refresh');
    //         window.location.reload();
    //     })
    // }
    getUserArticleAction()
    getFollowList()
})

onBeforeUnmount(() => {
    // localStorage.removeItem('hasRefreshed')
})


/* ------------------------------- 创建粉丝男女比例饼图 ------------------------------- */
// let asideCharts = ref(null)
// onMounted(() => {
//     let myChart = echarts.init(asideCharts.value)
//     myChart.setOption({
//         tooltip: {
//             trigger: 'item'
//         },
//         title: {
//             text: '粉丝男女比例',
//             left: 'center',
//             textStyle: {
//                 fontSize: 14
//             }
//         },
//         legend: {
//             top: 'bottom',
//             left: 'center'
//         },
//         series: [
//             {
//                 name: 'Access From',
//                 type: 'pie',
//                 radius: ['40%', '70%'],
//                 avoidLabelOverlap: false,
//                 itemStyle: {
//                     borderRadius: 10,
//                     borderColor: '#fff',
//                     borderWidth: 2
//                 },
//                 label: {
//                     show: false,
//                     position: 'center'
//                 },
//                 emphasis: {
//                     label: {
//                         show: true,
//                         fontSize: 20,
//                         fontWeight: 'bold'
//                     }
//                 },
//                 labelLine: {
//                     show: false
//                 },
//                 data: [
//                     { value: 1048, name: '男' },
//                     { value: 735, name: '女' },
//                     { value: 330, name: '保密' }
//                 ]
//             }
//         ]
//     })
// })

/* ---------------------------------- 创建点赞量收藏量图表 ---------------------------------- */
let top = ref(null)     //图表容器
let myChart = ref()     // 图表对象
const initMyChart = () => {
    myChart.value = echarts.init(top.value)
    // 绘制图表
    myChart.value.setOption({
        // 使用 dataZoom 组件
        dataZoom: [
            {
                type: 'slider', // 类型为滑动条
                start: 0,       // 数据窗口范围的起始百分比
                end: 100,       // 数据窗口范围的结束百分比
                orient: 'horizontal' // 水平布局
            },
            {
                type: 'inside', // 内置型数据区域缩放组件
                xAxisIndex: 0,  // 控制第一个 xAxis
                start: 0,       // 数据窗口范围的起始百分比
                end: 10         // 数据窗口范围的结束百分比
            }
        ],
        tooltip: {
            trigger: 'item'
        },
        legend: {
            bottom: '0',
            left: 'right',
            top: 'center',
            orient: 'vertical',
        },
        title: {
            text: '点赞量与收藏量',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {},
        xAxis: {
            data: echartsXList.value,
            axisLabel: {
                formatter: function (value, index) {
                    // 根据你的数据自定义格式化函数  
                    return value.slice(0, 5) + '...'; // 仅作为示例，截取字符串前三个字符  
                },
                // rotate: 45 // 标签旋转角度 
            }
        },
        yAxis: {
            min: 0, // 设置Y轴最小值  
            max: 30, // 设置Y轴最大值  
            splitNumber: 3, // 设置Y轴分割段数 
        },
        series: [
            {
                name: '点赞量',
                type: 'line',
                data: echartsYLike.value
            },
            {
                name: '收藏量',
                type: 'line',
                data: echartsYCollect.value
            }
        ]
    })
}



// 当echartsXList数据回来后刷新图表
watch(echartsXList, (newValue, oldValue) => {
    myChart.value.setOption({
        tooltip: {
            trigger: 'item'
        },
        legend: {
            bottom: '0',
            left: 'right',
            top: 'center',
            orient: 'vertical',
        },
        title: {
            text: '点赞量与收藏量',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {},
        xAxis: {
            data: newValue,
            axisLabel: {
                formatter: function (value, index) {
                    // 根据你的数据自定义格式化函数  
                    return value.slice(0, 5) + '...'; // 仅作为示例，截取字符串前三个字符  
                },
                // rotate: 45 // 标签旋转角度 
            }
        },
        yAxis: {
            min: 0, // 设置Y轴最小值  
            max: 30, // 设置Y轴最大值  
            splitNumber: 3, // 设置Y轴分割段数 
        },
        series: [
            {
                name: '点赞量',
                type: 'line',
                data: echartsYLike.value
            },
            {
                name: '收藏量',
                type: 'line',
                data: echartsYCollect.value
            }
        ]
    })
})


//点击导航栏分类
const changeAction = () => {
    switch (activeName.value) {
        case 'first':
            articleListCopy.value = articleList.value
            break
        case 'second':
            articleListCopy.value = articleList.value.filter(item => item.article_status === '0')
            break
        case 'third':
            articleListCopy.value = articleList.value.filter(item => item.article_status === '1')
            break
        case 'fourth':
            articleListCopy.value = articleList.value.filter(item => item.article_status === '2')
            break
    }
}

/* --------------------------------- 修改个人信息 --------------------------------- */
let drawer = ref(false)
const showDrawer = () => {
    drawer.value = true
}

// 头像上传成功后，重新请求用户信息，更新仓库中的数据信息
const handleAvatarSuccess = async () => {
    let data = await getUserInfoAPI(userInfo.value.user_id)
    if (data.code === 200) {
        // 把返回的userinfo存在仓库中
        dataStore.setUserInfo(data.data[0])
        ElMessage({
            type: 'success',
            message: '修改头像成功'
        })
    }

}

// 文字型用户信息失去焦点后，发起请求修改
const blurAction = async (type) => {
    let text = ''
    switch (type) {
        case 'user_name': text = userInfo.value.user_name; break;
        case 'user_gender': text = userInfo.value.user_gender; break;
        case 'user_email': text = userInfo.value.user_email; break;
        case 'user_introduction': text = userInfo.value.user_introduction; break;
    }
    let data = await updateUserTextAPI(userInfo.value.user_id, text, type)
    if (data.code === 200) {
        ElMessage({
            type: 'success',
            message: `修改成功`
        })
    }
}

/* ----------------------------- 获取当前用户的关注/粉丝列表 ----------------------------- */
let followList = ref([])    //关注列表
let fansList = ref([])  //粉丝列表
const getFollowList = async () => {
    let res = await followListAPI(userInfo.value.user_id)
    if (res.code === 200) {
        followList.value = res.data.followUserList
        fansList.value = res.data.fansUserList
    }
}
let asideListFlag = ref(false)
let listType = ref('follow')
const asideListAction = (lt) => {
    asideListFlag.value = true
    listType.value = lt
    // if (listType === 'follow') {

    // }
}

/* --------------------------------- 跳转到用户空间 -------------------------------- */
const toUserHomeAction = (user_id) => {
    router.push({ name: 'me', query: { user_id } })
}

// let infoDrawerRef = ref()
// let asideDrawerRef = ref()
// onBeforeUnmount(() => {
//     infoDrawerRef.value.handleClose()
//     asideDrawerRef.value.handleClose()
// })



</script>

<template>
    <div class="page">
        <!-- 个人信息弹窗 -->
        <el-drawer ref="infoDrawerRef" v-model="drawer" title="修改个人信息" direction="ltr" :size="isMobile ? '80%' : '30%'">
            <div class="update">
                <div class="avatar">
                    <el-upload class="avatar-uploader" :show-file-list="false" :action="AVATAR_URL"
                        :data="{ user_id: userInfo.user_id }" :on-success="handleAvatarSuccess">
                        <img class="avatar-area" :src="userInfo.user_avatar" alt="">
                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div>
                <div class="form">
                    <el-form label-position="top" label-width="auto" :model="userInfo">
                        <el-form-item label="用户名">
                            <el-input v-model="userInfo.user_name" @blur="blurAction('user_name')" />
                        </el-form-item>
                        <el-form-item label="性别">
                            <el-input v-model="userInfo.user_gender" @blur="blurAction('user_gender')" />
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <el-input v-model="userInfo.user_email" @blur="blurAction('user_email')" />
                        </el-form-item>
                        <el-form-item label="个性签名">
                            <el-input v-model="userInfo.user_introduction" @blur="blurAction('user_introduction')" />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </el-drawer>
        <!-- 关注粉丝列表弹窗 -->
        <el-drawer ref="asideDrawerRef" v-model="asideListFlag" :title="listType === 'follow' ? '关注列表' : '粉丝列表'"
            direction="ltr">
            <div class="update">
                <div class="list">
                    <div class="list-item" v-for="item in (listType === 'follow' ? followList : fansList)"
                        :key="item.user_id" @click="toUserHomeAction(item.user_id)">
                        <div class="item-avatar"><img :src="item.user_avatar" alt=""></div>
                        <div class="item-info">
                            <div class="info-name">{{ item.user_name }}</div>
                            <div class="info-email">{{ item.user_email }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </el-drawer>

        <div class="container">
            <!-- <div class="headers">
                <headers :userInfo="userInfo"></headers>
            </div>-->
            <div class="temp" v-show="!isMobile"></div>
            <div class="main">
                <div class="asideMobile" v-if="isMobile">
                    <div class="asideMobile-left">
                        <div class="left-avatar"><img :src="userInfo.user_avatar" alt=""></div>
                        <div class="left-info">
                            <div class="info-name">{{ userInfo.user_name }}</div>
                            <div class="info-email">{{ userInfo.user_email }}</div>
                            <div class="info-option">
                                <div @click="asideListAction('follow')">关注: {{ followList.length || 0 }}</div>
                                <div style="margin-left: 5px;" @click="asideListAction('fans')">粉丝: {{ fansList.length
                                    || 0 }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="asideMobile-right"><el-icon @click="showDrawer">
                            <Edit />
                        </el-icon></div>
                </div>
                <div class="aside" v-else>
                    <div class="aside-img">
                        <img :src="userInfo.user_avatar" alt="">
                    </div>
                    <div class="aside-name">{{ userInfo.user_name }}</div>
                    <div class="aside-option">
                        <div @click="asideListAction('follow')">关注: {{ followList.length || 0 }}</div>
                        <div @click="asideListAction('fans')">粉丝: {{ fansList.length || 0 }}</div>
                    </div>
                    <div class="aside-content">
                        <div class="content-text">{{ userInfo.user_introduction }}</div>
                        <div class="content-text">我的地址：{{ userInfo.user_address }}</div>
                        <div class="content-text">性别：{{ userInfo.user_gender }}</div>
                        <div class="content-text">我的邮箱：{{ userInfo.user_email }}</div>
                    </div>
                    <div class="aside-btn">
                        <el-button @click="showDrawer">修改信息</el-button>
                    </div>
                    <div class="aside-echarts" ref="asideCharts"></div>
                </div>
                <div class="right">
                    <div ref="top" class="top"></div>
                    <div class="content">
                        <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="changeAction">
                            <el-tab-pane label="我的文章" name="first"></el-tab-pane>
                            <el-tab-pane label="待审核" name="second"></el-tab-pane>
                            <el-tab-pane label="已通过" name="third"></el-tab-pane>
                            <el-tab-pane label="已驳回" name="fourth"></el-tab-pane>
                        </el-tabs>
                        <div class="content-article">
                            <div class="article-item" v-for="item in articleListCopy" :key="item.article_id">
                                <div class="item-left">
                                    <div class="left-title">{{ item.article_title }}</div>
                                    <div class="left-introduction">{{ item.article_introduction }}</div>
                                    <div class="left-author">
                                        <div class="author-name">{{ nyr(new Date(item.article_time * 1), '-') }}</div>
                                        <div class="author-lc">
                                            <!-- <el-icon>
                                                <Pointer />
                                            </el-icon> -->
                                            <div>
                                                <i class="iconfont icon-dianzan_kuai"></i>
                                                {{ item.article_like }}
                                            </div>
                                            <div>
                                                <i class="iconfont icon-shoucang"></i>
                                                {{ item.article_like }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="item-right"><img :src="item.article_coverimg" alt=""></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


        </div>
    </div>
</template>

<style scoped lang='scss'>
@import url('./user.scss');
</style>